<script setup>
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { constantRoutes } from '@/router/routes.js'

  // 表格数据相关
  const menuList = ref([])
  const loading = ref(false)

  // 对话框相关
  const dialogVisible = ref(false)
  const dialogTitle = ref('添加菜单')
  const isEdit = ref(false)
  const currentMenuId = ref(null)
  const currentParentId = ref(null)

  // 表单数据
  const menuForm = reactive({
    menuId: '',
    parentId: 0,
    menuName: '',
    path: '',
    level: 0
  })

  // 表单引用
  const menuFormRef = ref(null)

  // 表单校验规则
  const rules = reactive({
    menuName: [
      { required: true, message: '请输入菜单名称', trigger: 'blur' }
    ],
    path: [
      { required: true, message: '请输入权限值', trigger: 'blur' }
    ]
  })

  // 初始化菜单数据
  const initMenuData = () => {
    // 从路由配置中提取菜单数据
    const formatMenuData = (routes, parentId = 0, level = 0) => {
      let result = []
      routes.forEach((route, index) => {
        // 跳过隐藏的菜单
        if (route.meta?.hidden) return

        const menuItem = {
          menuId: `${parentId}-${index}`,
          parentId: parentId,
          menuName: route.meta?.title || route.name || '未命名',
          path: route.path,
          createTime: '2025-01-15 10:30:00',
          updateTime: '2025-06-20 14:45:00',
          level: level,
          children: []
        }

        // 递归处理子菜单
        if (route.children && route.children.length > 0) {
          const children = formatMenuData(route.children, menuItem.menuId, level + 1)
          if (children.length > 0) {
            menuItem.children = children
          }
        }

        result.push(menuItem)
      })
      return result
    }

    // 过滤掉登录页面和404页面等不需要在菜单管理中显示的路由
    const visibleRoutes = constantRoutes.filter(route =>
      route.path !== '/login' &&
      route.path !== '/404' &&
      route.path !== '/:pathMatch(.*)*'
    )

    menuList.value = formatMenuData(visibleRoutes)
  }

  // 处理添加菜单
  const handleAddMenu = (parentMenu = null) => {
    dialogTitle.value = parentMenu ? '添加子菜单' : '添加菜单'
    isEdit.value = false
    currentMenuId.value = null
    currentParentId.value = parentMenu ? parentMenu.menuId : 0

    // 重置表单
    Object.assign(menuForm, {
      menuId: '',
      parentId: currentParentId.value,
      menuName: '',
      path: '',
      level: parentMenu ? parentMenu.level + 1 : 0
    })

    dialogVisible.value = true
  }

  // 处理编辑菜单
  const handleEditMenu = (menu) => {
    dialogTitle.value = '编辑菜单'
    isEdit.value = true
    currentMenuId.value = menu.menuId
    currentParentId.value = menu.parentId

    // 填充表单数据
    Object.assign(menuForm, {
      menuId: menu.menuId,
      parentId: menu.parentId,
      menuName: menu.menuName,
      path: menu.path,
      level: menu.level
    })

    dialogVisible.value = true
  }

  // 处理删除菜单
  const handleDeleteMenu = async (menuId) => {
    try {
      loading.value = true

      // 模拟异步删除过程
      setTimeout(() => {
        // 递归删除菜单及其子菜单
        const deleteMenuRecursive = (menuArray) => {
          for (let i = 0; i < menuArray.length; i++) {
            if (menuArray[i].menuId === menuId) {
              menuArray.splice(i, 1)
              return true
            }
            if (menuArray[i].children && menuArray[i].children.length > 0) {
              if (deleteMenuRecursive(menuArray[i].children)) {
                // 如果子菜单数组为空，删除该属性
                if (menuArray[i].children.length === 0) {
                  delete menuArray[i].children
                }
                return true
              }
            }
          }
          return false
        }

        const success = deleteMenuRecursive(menuList.value)

        if (success) {
          ElMessage.success('删除成功')
        } else {
          ElMessage.error('删除失败，未找到该菜单')
        }

        loading.value = false
      }, 500)
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
      loading.value = false
    }
  }

  // 处理表单提交
  const handleSubmit = async () => {
    try {
      // 验证表单
      if (!menuForm.menuName.trim() || !menuForm.path.trim()) {
        ElMessage.error('请填写必填项')
        return
      }

      loading.value = true

      // 模拟异步提交过程
      setTimeout(() => {
        const now = new Date().toLocaleString('zh-CN')

        if (isEdit.value) {
          // 编辑菜单
          const updateMenuRecursive = (menuArray) => {
            for (const menu of menuArray) {
              if (menu.menuId === currentMenuId.value) {
                // 更新菜单信息
                menu.menuName = menuForm.menuName
                menu.path = menuForm.path
                menu.updateTime = now
                return true
              }
              if (menu.children && menu.children.length > 0) {
                if (updateMenuRecursive(menu.children)) {
                  return true
                }
              }
            }
            return false
          }

          const success = updateMenuRecursive(menuList.value)

          if (success) {
            ElMessage.success('更新成功')
          } else {
            ElMessage.error('更新失败，未找到该菜单')
          }
        } else {
          // 添加菜单
          const newMenu = {
            menuId: `${currentParentId.value}-${Date.now()}`,
            parentId: currentParentId.value,
            menuName: menuForm.menuName,
            path: menuForm.path,
            createTime: now,
            updateTime: now,
            level: menuForm.level,
            children: []
          }

          // 如果是添加子菜单，找到父菜单并添加
          if (currentParentId.value !== 0) {
            const addToParentMenu = (menuArray) => {
              for (const menu of menuArray) {
                if (menu.menuId === currentParentId.value) {
                  if (!menu.children) {
                    menu.children = []
                  }
                  menu.children.push(newMenu)
                  return true
                }
                if (menu.children && menu.children.length > 0) {
                  if (addToParentMenu(menu.children)) {
                    return true
                  }
                }
              }
              return false
            }

            const success = addToParentMenu(menuList.value)

            if (success) {
              ElMessage.success('添加成功')
            } else {
              ElMessage.error('添加失败，未找到父菜单')
            }
          } else {
            // 添加根菜单
            menuList.value.push(newMenu)
            ElMessage.success('添加成功')
          }
        }

        // 关闭对话框
        dialogVisible.value = false
        loading.value = false
      }, 500)
    } catch (error) {
      console.error('表单提交失败:', error)
      ElMessage.error('操作失败')
      loading.value = false
    }
  }

  // 初始化
  onMounted(() => {
    initMenuData()
  })
</script>
<template>
  <div class="menu-management-container">

    <!-- 菜单表格 -->
    <el-card
      class="menu-table-card"
      style="margin-top: 20px;"
    >
      <el-table
        :data="menuList"
        style="width: 100%;"
        row-key="menuId"
        border
        v-loading="loading"
      >
        <el-table-column
          prop="menuName"
          label="名称"
          width="180"
        ></el-table-column>
        <el-table-column
          prop="path"
          label="权限值"
          width="200"
        ></el-table-column>
        <el-table-column
          prop="updateTime"
          label="修改时间"
          width="200"
        ></el-table-column>
        <el-table-column
          label="操作"
          fixed="right"
          width="250"
        >
          <template #default="{ row }">
            <el-button
              type="primary"
              @click="handleAddMenu(row)"
              size="small"
              :disabled="row.level === 4"
              style="margin-right: 5px;"
            >
              {{ row.level === 3 ? '添加功能' : '添加菜单' }}
            </el-button>
            <el-button
              type="primary"
              @click="handleEditMenu(row)"
              size="small"
              style="margin-right: 5px;"
            >
              编辑
            </el-button>
            <el-popconfirm
              :title="`你确定要删除${row.menuName}?`"
              width="260px"
              @confirm="handleDeleteMenu(row.menuId)"
            >
              <template #reference>
                <el-button
                  type="danger"
                  size="small"
                >
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑菜单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        ref="menuFormRef"
        :model="menuForm"
        :rules="rules"
        label-width="100px"
        style="margin-top: 20px;"
        size="small"
      >
        <el-form-item
          label="名称"
          prop="menuName"
        >
          <el-input
            placeholder="请输入菜单名称"
            v-model="menuForm.menuName"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="权限值"
          prop="path"
        >
          <el-input
            placeholder="请输入权限数值"
            v-model="menuForm.path"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="handleSubmit"
            :loading="loading"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<style scoped></style>